package wcpackage.webapplication;

import org.apache.wicket.Request;
import org.apache.wicket.Response;
import org.apache.wicket.Session;
import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.spring.injection.annot.SpringComponentInjector;
import org.odlabs.wiquery.utils.WiQueryWebApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import wcpackage.domain.dao.UserDAO;
import wcpackage.domain.entities.User;
import wcpackage.webapplication.security.UserAuthorizationStrategy;
import wcpackage.webapplication.view.loginpage.LoginPage;
import wcpackage.webapplication.view.welcomepage.WelcomePage;

/**
 * User: rabbit
 * Date: Jun 3, 2009
 * Time: 10:34:45 PM
 */
@Component(value = "wicketApplication")
public class Application extends WiQueryWebApplication {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private UserDAO userDAO;

    @Override
    protected void init() {
        super.init();
        addComponentInstantiationListener(new SpringComponentInjector(this, applicationContext, true));
        initAuthorizationStartegy();
        mountBookmarkablePages();
    }

    private void initAuthorizationStartegy() {
        UserAuthorizationStrategy authorizationStrategy = new UserAuthorizationStrategy(userDAO);
        getSecuritySettings().setAuthorizationStrategy(authorizationStrategy);
        getSecuritySettings().setUnauthorizedComponentInstantiationListener(authorizationStrategy);
    }

    private void mountBookmarkablePages() {
        try {
            mountBookmarkablePage("login", LoginPage.class);
        } catch (WicketRuntimeException exception) {
            // this runtime happens with junit test, as init() method is
            // executed with every test and there is simply no way to unmount
            // pages
        }
    }

    @Override
    public Session newSession(Request request, Response response) {
        return new UserSession(request, User.GUEST_USER);
    }

    @Override
    public Class getHomePage() {
        return WelcomePage.class;
    }
}
